const state = {
	sessions: [], // 处理后的会话列表
	rawSessions: [], // 原始的会话列表
	defaultUserLogo: ``, // 默认头像
	userInfo: {}, // 登录用户信息
	currentSession: '', // 正在聊天 sessionId 不带聊天类型
	currentChatTo: '', // 正在聊天 sessionId 带聊天类型
	currentChatInfo: '', // 正在聊天所有信息
	personList: {}, // 所有有信息的人的列表
	blackList: [], // 黑名单列表
	unreadInfo: {}, // 未读信息，包含已、未订阅的账户数
	unreadTotalNum: 0, // 未读信息总数
	rawMessageList: {}, // 所有的聊天列表都在里面
	notificationList: {
		system: [],
		custom: []
	}, // 系统通知，分为自定义消息和系统消息
	netcallGroupCallInfo: {} // 群组音视频被叫时通知信息
}

const mutations = {
	setRawSessions(state, value) {
		state.rawSessions = value
	},
	setUnreadInfo(state, value) {
		state.unreadInfo = value
	},
	setUnreadTotalNum(state, value) {
		state.unreadTotalNum = value
		if (value == 0) {
			uni.removeTabBarBadge({
				index: 3
			})
		} else {
			let txtVal = '';
			if (value > 0 && value < 100) {
				txtVal = value.toString()
			} else if (value > 99) {
				txtVal = '99+'
			}
			uni.setTabBarBadge({
				index: 3,
				text: txtVal
			})	
		}
	},
	setCurrentChatTo(state, value) {
		state.currentChatTo = value
	},
	setCurrentSession(state, value) {
		state.currentSession = value
	},
	setRawMessageList(state, value) {
		state.rawMessageList = value
	}
}

const actions = {
	// 会话更新
	Session_update(context, args) {
		let list = args
		context.commit('setRawSessions', list);
	},
	// UnreadInfo：更新未读消息数
	SessionUnreadInfo_update(context, sessions) {
		let totalNum = 0
		sessions.map((item,index) => {
			if (item.unreadCount) {
				state.unreadInfo[item.conversationID] = item.unreadCount
				totalNum = totalNum + item.unreadCount
			}
		})
		context.commit('setUnreadInfo', state.unreadInfo)
		context.commit('setUnreadTotalNum', totalNum)
	},
	// 设置当前聊天对象
	CurrentChatTo_Change(context, args) {
		context.commit('setCurrentChatTo', args.session)
		context.commit('setCurrentSession', args.account)
	},
	// RawMessageList：存储原始消息
	RawMessageList_Add_Msg(context, args) {
		let msg = args.msg
		let rawMessageList = Object.assign({}, state.rawMessageList)
		let sessionId = msg.conversationID
		if (!rawMessageList[sessionId]) {
			rawMessageList[sessionId] = {}
		}
		rawMessageList[sessionId][msg.time] = Object.assign({}, msg)
		if (state.currentChatTo === msg.conversationID) { // 当前会话
			getApp().globalData.tim.setMessageRead({conversationID: msg.conversationID})
		}
	
		context.commit('setRawMessageList', rawMessageList)
	},
}

const getters = {
	conversationAvatar: (state) => (conversationID) => {
		if (state.rawSessions && state.rawSessions.length > 0) {
			const targetSessions = state.rawSessions.filter(i => i.conversationID === conversationID);
			if (targetSessions && targetSessions.length > 0) {
				return targetSessions[0].userProfile.avatar;
			}
		}
		return '';
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters
}